package com.woniuxy.service.impl;

import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.service.QiniuService;
import com.woniuxy.utils.FileUtil;
import com.woniuxy.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author: 杜昊男  <br/>
 * Date: 2022/3/7:19:54  <br/>
 * Description:
 */
@Service
public class QiniuServiceImpl implements QiniuService {
    @Autowired
    private QiniuUtil qiniuUtil;
    /*
     * Description : 上传图片的方法
     * ChangeLog : 1. 创建 (2022/3/9 1:34 [10604]);
     ** @param null
     * *  @return null
    */
    @Override
    public ResponseEntity upload(MultipartFile file, HttpServletRequest request) {
        if(file.isEmpty()) {
            return ResponseEntity.error("文件不能为空");
        }
        //获取文件后缀名
        String fileName= file.getOriginalFilename();
        String suffix  = fileName.substring(fileName.lastIndexOf(".")+1);
        String fileUrl="";
        //根据后缀名判断使用哪个上传方法
        try {
            if (existStr(FileUtil.IMAGE_FILE_EXTD,suffix)) {
                System.out.println("img*******"+fileName);
                fileUrl=qiniuUtil.saveImage(file);
            }else if (existStr(FileUtil.VIDEO_FILE_EXTD, suffix)) {
                System.out.println("video********"+fileName);
                fileUrl=qiniuUtil.saveVideo(file);
            }else if (existStr(FileUtil.OTHER_FILE_EXTD, suffix)) {
                System.out.println("other**********"+fileName);
                fileUrl=qiniuUtil.saveOther(file);
            }else {
                return ResponseEntity.error("不支持该文件类型");
            }
            return  ResponseEntity.success("上传成功",fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.error("上传失败");
    }
    public static boolean existStr(String[] array,String str) {
        List<String> aList = Arrays.asList(array);
        return aList.contains(str);
    }
}
